package com.anti.modular.bus.billwater.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.billwater.entity.BillWater;
import com.anti.modular.bus.billwater.enums.BillWaterExceptionEnum;
import com.anti.modular.bus.billwater.param.BillWaterOnParam;
import com.anti.modular.bus.billwater.param.BillWaterParam;
import com.anti.modular.bus.billwater.result.BillWaterDetailExcel;
import com.anti.modular.bus.billwater.result.BillWaterDetailResult;
import com.anti.modular.bus.billwater.result.BillWaterExcelResult;
import com.anti.modular.bus.billwater.service.BillWaterService;
import com.anti.modular.bus.billwaterdetail.entity.BillWaterDetail;
import com.anti.modular.bus.billwaterdetail.service.BillWaterDetailService;
import com.anti.modular.bus.housebill.entity.Cty;
import com.anti.modular.bus.housebill.entity.HouseBillExcel;
import com.anti.modular.sys.auth.pojo.SysLoginUser;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账单流水service接口实现类
 *
 * @author anti
 * @date 2021-04-24 13:44:46
 */
@Service
public class BillWaterServiceImpl implements BillWaterService {
    @Resource
    DBUtils dbUtils;
    @Resource
    BillWaterDetailService billWaterDetailService;

    @Override
    public BillWater getById(BillWaterParam billWaterParam){
        String sql="select * from bill_water where id =? ";
        return dbUtils.get(sql,BillWater.class,billWaterParam.getId());
    }

    @Override
    public PageResult page(PageParam pageParam, BillWaterOnParam billWaterParam) {
        StringBuilder sb=new StringBuilder("select a1.* from bill_water a1 where status=0 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(billWaterParam)) {
            String startTime = billWaterParam.getDateStrStart();
            String endTime = billWaterParam.getDateStrEnd();
            if(ObjectUtil.isNotEmpty(startTime)&&ObjectUtil.isNotEmpty(endTime)) {
                // 根据房间名 查询
                if (ObjectUtil.isNotEmpty(billWaterParam.getReceiveDateType())) {
                    int receiveDateType = billWaterParam.getReceiveDateType();
                    if (receiveDateType==1){
                        sb.append(" and  DATE_FORMAT(a1.receive_date,'%Y-%m-%d')<=DATE_FORMAT(?,'%Y-%m-%d') and DATE_FORMAT(a1.receive_date,'%Y-%m-%d')>=DATE_FORMAT(?,'%Y-%m-%d')");
                        param.add(endTime);
                        param.add(startTime);
                    }else {
                        sb.append(" and  DATE_FORMAT(a1.should_receive_date,'%Y-%m-%d')<=DATE_FORMAT(?,'%Y-%m-%d') and DATE_FORMAT(a1.should_receive_date,'%Y-%m-%d')>=DATE_FORMAT(?,'%Y-%m-%d')");
                        param.add(endTime);
                        param.add(startTime);
                    }
                }
            }
            if (ObjectUtil.isNotEmpty(billWaterParam.getBillInOutType())) {
                int billInOutType = billWaterParam.getBillInOutType();
                if (0!=billInOutType){
                    sb.append(" and a1.bill_in_out_type = ?");
                    param.add(billInOutType);
                }
            }
            // 根据来源 （字典 bill_water_source） 查询
            if (ObjectUtil.isNotEmpty(billWaterParam.getSource())) {
                int source = billWaterParam.getSource();
                if (0!=source){
                    sb.append(" and a1.source = ?");
                    param.add(source);
                }
            }
            if (ObjectUtil.isNotEmpty(billWaterParam.getTransaction())) {
                int transaction = billWaterParam.getTransaction();
                if (0!=transaction){
                    sb.append(" and a1.transaction = ?");
                    param.add(transaction);
                }
            }
            if (ObjectUtil.isNotEmpty(billWaterParam.getAuditFlag())) {
                int auditFlag = billWaterParam.getAuditFlag();
                if (2!=auditFlag){
                    sb.append(" and a1.audit_flag = ?");
                    param.add(auditFlag);
                }
            }
            // 根据交易方式编码 查询
            if (ObjectUtil.isNotEmpty(billWaterParam.getStateId())) {
                Long stateId = billWaterParam.getStateId();
                Long roomId = billWaterParam.getRoomId();
                if (0!=stateId&&0==roomId){
                    sb.append(" and a1.id in (select bill_water_id from bill_water_room where room_id in (select id from bus_room where status=0 and estateid = ?))");
                    param.add(stateId);
                }
                if (0!=stateId&&0!=roomId){
                    sb.append(" and a1.id in (select bill_water_id from bill_water_room where room_id =? )");
                    param.add(roomId);
                }
            }
        }
        sb.append(" order by a1.create_time desc");
        return dbUtils.query(pageParam,sb.toString(),BillWater.class,param.toArray());
    }


    @Override
    public List<BillWaterExcelResult> getExportData(BillWaterOnParam billWaterParam) {
        StringBuilder sb=new StringBuilder("select a1.*,(select name from bus_means_of_transaction where id =a1.transaction) as transaction_nam,(select value from  sys_dict_data where code = a1.source and type_id=1358470065111253001) as  source_name from bill_water a1 where 1=1 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(billWaterParam)) {
            String startTime = billWaterParam.getDateStrStart();
            String endTime = billWaterParam.getDateStrEnd();
            if(ObjectUtil.isNotEmpty(startTime)&&ObjectUtil.isNotEmpty(endTime)) {
                // 根据房间名 查询
                if (ObjectUtil.isNotEmpty(billWaterParam.getReceiveDateType())) {
                    int receiveDateType = billWaterParam.getReceiveDateType();
                    if (receiveDateType==1){
                        sb.append(" and  DATE_FORMAT(a1.receive_date,'%Y-%m-%d')<=DATE_FORMAT(?,'%Y-%m-%d') and DATE_FORMAT(a1.receive_date,'%Y-%m-%d')>=DATE_FORMAT(?,'%Y-%m-%d')");
                        param.add(endTime);
                        param.add(startTime);
                    }else {
                        sb.append(" and  DATE_FORMAT(a1.should_receive_date,'%Y-%m-%d')<=DATE_FORMAT(?,'%Y-%m-%d') and DATE_FORMAT(a1.should_receive_date,'%Y-%m-%d')>=DATE_FORMAT(?,'%Y-%m-%d')");
                        param.add(endTime);
                        param.add(startTime);
                    }
                }
            }
            if (ObjectUtil.isNotEmpty(billWaterParam.getBillInOutType())) {
                int billInOutType = billWaterParam.getBillInOutType();
                if (0!=billInOutType){
                    sb.append(" and a1.bill_in_out_type = ?");
                    param.add(billInOutType);
                }
            }
            // 根据来源 （字典 bill_water_source） 查询
            if (ObjectUtil.isNotEmpty(billWaterParam.getSource())) {
                int source = billWaterParam.getSource();
                if (0!=source){
                    sb.append(" and a1.source = ?");
                    param.add(source);
                }
            }
            if (ObjectUtil.isNotEmpty(billWaterParam.getTransaction())) {
                int transaction = billWaterParam.getTransaction();
                if (0!=transaction){
                    sb.append(" and a1.transaction = ?");
                    param.add(transaction);
                }
            }
            if (ObjectUtil.isNotEmpty(billWaterParam.getAuditFlag())) {
                int auditFlag = billWaterParam.getAuditFlag();
                if (2!=auditFlag){
                    sb.append(" and a1.audit_flag = ?");
                    param.add(auditFlag);
                }
            }
            // 根据交易方式编码 查询
            if (ObjectUtil.isNotEmpty(billWaterParam.getStateId())) {
                Long stateId = billWaterParam.getStateId();
                Long roomId = billWaterParam.getRoomId();
                if (0!=stateId&&0==roomId){
                    sb.append(" and a1.id in (select bill_water_id from bill_water_room where room_id in (select id from bus_room where status=0 and estateid = ?))");
                    param.add(stateId);
                }
                if (0!=stateId&&0!=roomId){
                    sb.append(" and a1.id in (select bill_water_id from bill_water_room where room_id =? )");
                    param.add(roomId);
                }
            }
        }
        sb.append(" order by a1.create_time desc");
        List<BillWaterExcelResult> query = dbUtils.query(sb.toString(), BillWaterExcelResult.class, param.toArray());
        ArrayList<Long> ids = CollectionUtil.newArrayList();
        query.forEach(item-> {
            ids.add(item.getId());
        });
        if (ids.size()>0){
            List<BillWaterDetailExcel> byIds = billWaterDetailService.getByIds(ids);
            for (int i = 0; i < query.size(); i++) {
                BillWaterExcelResult houseBillExcel = query.get(i);
                List<BillWaterDetailExcel> ctyList = byIds.stream().filter(item -> item.getBillWaterId().equals(houseBillExcel.getId())).collect(Collectors.toList());
                ctyList.forEach(ct->{
                    if (ct.getBillInOutType().intValue()==2){
                        ct.setAmount(ct.getAmount().negate());
                    }
                });
                houseBillExcel.setDetailList(ctyList);
            }
        }
        return query;
    }

    @Override
    public List<BillWater> list(BillWaterParam billWaterParam) {
        String sql="";
        return dbUtils.query(sql,BillWater.class);
    }

    @Override
    public Long add(BillWaterParam billWaterParam) {
        BillWater billWater = new BillWater();
        BeanUtil.copyProperties(billWaterParam, billWater);
        String string = dbUtils.insertKey(billWater).toString();
        return Long.parseLong(string);
    }

    @Override
    public Long add(BillWater billWater) {
        String string = dbUtils.insertKey(billWater).toString();
        return Long.parseLong(string);
    }

    public void delete(BillWaterParam billWaterParam) {
        String sql="delete  from bill_water where id =? ";
        dbUtils.execSql(sql,billWaterParam.getId());
    }

    @Override
    public void deleteAllByType(Long id, String tableName) {
        String sql="delete from bill_water_room where bill_water_id in (select id from bill_water where bill_table=? and bill_id=? and status=0)";
        dbUtils.execSql(sql,tableName,id);
        Date date = new Date();
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        String detail="update bill_water_detail set status=2,update_time=?,update_user=? where bill_water_id in (select id from bill_water where bill_table=? and bill_id=? and status=0)";
        dbUtils.execSql(detail,date,sysLoginUserId,tableName,id);
        String main="update bill_water set status=2,update_time=?,update_user=? where bill_table=? and bill_id=? and status=0";
        dbUtils.execSql(main,date,sysLoginUserId,tableName,id);

    }

    public void edit(BillWaterParam billWaterParam) {
        BillWater billWater = this.queryBillWater(billWaterParam);
        BeanUtil.copyProperties(billWaterParam, billWater);
        dbUtils.update(billWater);
    }

    @Override
    public BillWater detail(BillWaterParam billWaterParam) {
        return this.queryBillWater(billWaterParam);
    }

    @Override
    public BillWaterDetailResult getBillWaterDetail(Long id) {
        String sql="select * from bill_water where id =? ";
        BillWaterDetailResult first = dbUtils.getFirst(sql, BillWaterDetailResult.class,id);
        String sqlDetail="select * from bill_water_detail where bill_water_id =? and status=0";
        List<BillWaterDetail> query = dbUtils.query(sqlDetail, BillWaterDetail.class, id);
        query.forEach(item->{
            int i = item.getBillInOutType().intValue();
            if (i!=1){
                item.setAmount(item.getAmount().negate());
            }
        });
        first.setDetailList(query);
        return first;
    }

    @Override
    public void editShenHe(Long id,Integer type) {
        Date date = new Date();
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        String upSql="update bill_water set audit_flag=?, audit_id=?, audit_name=?,audit_time=?,update_time=?,update_user=? where id =?";
        if (type.intValue() == 1) {
            dbUtils.execSql(upSql,1,sysLoginUser.getId(),sysLoginUser.getName(),date,date,sysLoginUser.getId(),id);
        }else {
            dbUtils.execSql(upSql,0,null,null,null,date,sysLoginUser.getId(),id);
        }
    }

    /**
     * 获取账单流水
     *
     * @author anti
     * @date 2021-04-24 13:44:46
     */
    private BillWater queryBillWater(BillWaterParam billWaterParam) {
        BillWater billWater = this.getById(billWaterParam);
        if (ObjectUtil.isNull(billWater)) {
            throw new BusinessException(BillWaterExceptionEnum.NOT_EXIST);
        }
        return billWater;
    }


}
